#!/usr/bin/python2.7
#-*-encoding:utf8-*-
# Import smtplib for the actual sending function
import smtplib,ConfigParser,os,sys,inspect
from Checks import Check
import text_format

# Here are the email package modules we'll need
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart


config_file = 'mail_detail.conf'
config = ConfigParser.RawConfigParser()
config.read(config_file)

mail_from = config.get('from','From')
mail_to = config.get('To','To')

mail_to = mail_to.split(',')
print mail_to
mail_subti = config.get('subtitle','sub_title')

print 'Mail from:',mail_from,'\n To: ',mail_to,' \nsubtitle:',mail_subti

#S1. warning interface.

check_info = Check()
warning_info = []

#obtain def functions.
for func in dir(check_info):
    if '__' not in func and inspect.ismethod(getattr(check_info,func)):
        cmd = 'check_info.'+func+'()'
        a=eval(cmd)
        try:
            if a[0]:
                print a[1]
                warning_info.append(a[1])
        except:
            print func,' returns nothing.'
            pass

#S2. Prepare the mail format. 

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart('Disk Monitor System')


msg['Content-type'] = 'text/html'
msg['From'] = mail_from
msg['To'] = COMMASPACE.join(mail_to)
msg['Subject'] = mail_subti
msg.preamble = 'DiskMonitor'

msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)

msgText = MIMEText(text_format.html(warning_info), 'html')
msgAlternative.attach(msgText)



#S3. Add picture. Assume we know that the image files are all in JPG fromat

jpgdir = 'pic'
jpgfiles = os.listdir(jpgdir)
i = 1

for file in jpgfiles:
    # Open the files in binary mode. Let the MIMEImage class automatically
    # guess the specific image type.
    with open(os.path.join(jpgdir, file), 'rb') as fp:
        img = MIMEImage(fp.read())
        img.add_header('Content-ID', '<image{n}>'.format(n=i))
        i += 1
    msg.attach(img)



#S4. Send the email via our own SMTP server.

if len(warning_info) > 0:
    s = smtplib.SMTP('localhost')
    s.sendmail(mail_from, mail_to, msg.as_string())
    s.quit()
